{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "\n",
    "from sklearn.datasets import load_breast_cancer\n",
    "\n",
    "cancer=load_breast_cancer()  #加载乳腺癌数据\n",
    "X=cancer.data   #data中是数据样本\n",
    "y=cancer.target  #target是样本的标签\n",
    "\n",
    "print(X.shape,y.shape)   #查看样本的组成情况\n",
    "\n",
    "print(y[y==1].size,y[y==0].size)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.svm import SVC\n",
    "\n",
    "X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2)  #划分训练集和测试集\n",
    "\n",
    "model=SVC(C=1.0,kernel='rbf',gamma=0.1) #创建一个C=1，用gamma=0.1的高斯核函数的SVM模型\n",
    "\n",
    "model.fit(X_train,y_train)  #训练模型\n",
    "\n",
    "train_score=model.score(X_train,y_train)  #计算模型得分，并输出\n",
    "test_score=model.score(X_test,y_test)\n",
    "\n",
    "print(\"train score: {0}; test score: {1}\".format(train_score,test_score))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#使用GridSearchCV来寻找最佳参数\n",
    "from sklearn.model_selection import GridSearchCV\n",
    "\n",
    "gammas=np.linspace(0,0.005,30)  #设定gamma值的取值区间\n",
    "param_grid={'gamma':gammas}  #参数矩阵\n",
    "\n",
    "model=GridSearchCV(SVC(),param_grid,cv=5)\n",
    "model.fit(X_train,y_train)\n",
    "\n",
    "print(\"best param: {0}; best score: {1}\".format(model.best_params_,model.best_score_))  #查看最优参数及最佳得分"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model=SVC(C=1.0,kernel='poly',degree=2)  #用二阶多项式核函数建立模型\n",
    "\n",
    "model.fit(X_train,y_train)\n",
    "\n",
    "train_score=model.score(X_train,y_train)\n",
    "test_score=model.score(X_test,y_test)\n",
    "\n",
    "print(\"train score: {0}; test score: {1}\".format(train_score,test_score))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
